package server.jdbcdao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import server.core.Group;
import server.dao.GroupDAO;
import server.idatasource.DataSourceFactory;
import server.idatasource.IGroupDataSource;

public class GroupJdbcDAO implements GroupDAO {

	@Override
	public List<Group> getAllGroups() {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IGroupDataSource groupData = ds.getGroupDataSource();

		List<List<String>> result = groupData.getAllGroups();
		Iterator<List<String>> it1 = result.iterator();
		Group group;
		List<Group> groupList = new ArrayList<Group>();

		while (it1.hasNext()) {
			Iterator<String> it2 = it1.next().iterator();
			group = new Group();
			group.setId(Integer.parseInt(it2.next()));
			group.setName(it2.next());
			group.setPassword(it2.next());
			groupList.add(group);
		}
		return groupList;
	}

	/*Inserts a new group into the database, given in the argument. Returns a string, with the
	 * value "OK" if the operation was successful, else returns "ERROR".*/
	@Override
	public String insertGroup(Group group) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IGroupDataSource groupData = ds.getGroupDataSource();

		return groupData.insertGroup(group.getName(), group.getPassword());
	}

	/*Deletes a group from database, having the groupname given in the argument. Returns a string, with the
	 * value "OK" if the operation was successful, else returns "ERROR".*/
	@Override
	public String deleteGroup(String groupName) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IGroupDataSource groupData = ds.getGroupDataSource();

		return groupData.deleteGroup(groupName);
	}

	/*Updates the group given in the argument, in the database. Returns a string, with the
	 * value "OK" if the operation was successful, else returns "ERROR".*/
	@Override
	public String updateGroup(Group group) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IGroupDataSource groupData = ds.getGroupDataSource();

		return groupData.updateGroup(group.getId(), group.getName(), group.getPassword());
	}

}
